<?php


namespace app\job;


use app\model\coach\CoachWithdrawRecordModel;
use app\model\coach\UserCoachModel;
use app\model\partner\EscortMenuReserveOrderModel;
use app\model\partner\UserPartnerModel;
use app\model\user\PartnerWithdrawRecordModel;
use app\service\config\ConfigService;
use app\service\utils\WeiXinOfficialService;
use think\queue\Job;
use zjkal\TimeHelper;

class WeiXinTemplateMsgJob
{
    /**
     * fire方法是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        // 如有必要,可以根据业务需求和数据库中的最新数据,判断该任务是否仍有必要执行.
        $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
        if (!$isJobStillNeedToBeDone) {
            $job->delete();
            return;
        }

        $isJobDone = $this->doHelloJob($data);

        if ($isJobDone) {
            //如果任务执行成功， 记得删除任务
            $job->delete();
        } else {
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
                $job->delete();
                // 也可以重新发布这个任务
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }


    /**
     * 有些消息在到达消费者时,可能已经不再需要执行了
     * @param array|mixed $data 发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function checkDatabaseToSeeIfJobNeedToBeDone($data)
    {
        return true;
    }

    /**
     * 执行业务
     * @param $data
     * @return bool
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function doHelloJob($data)
    {
        // 根据消息中的数据进行实际的业务处理...
        $msgType = $data['msg_type'];
        $id = $data['id'];
        $domain = ConfigService::getConfigValue('domain');

        $weiXinOfficialService = new WeiXinOfficialService();
        // 新订单通知
        if ($msgType == 'new_order') {
            $orderInfo = EscortMenuReserveOrderModel::with('menuOrder')->find($id);
            // 陪驾订单
            if ($orderInfo['order_type'] == 1) {
                if ($orderInfo['coach_user_id']) {
                    $openIdArr = UserPartnerModel::where('id', $orderInfo['coach_user_id'])->column('openid');
                } else {
                    $openIdArr = UserPartnerModel::whereIn('user_type', [0, 2])
                        ->where('status', 1)
                        ->where('is_forbid', 0)
                        ->where('openid', '<>', '')
                        ->where('city', $orderInfo['city_id'])
                        ->column('openid');
                }

                $data = [
                    'keyword1' => $orderInfo['order_sn'],
                    'keyword2' => '陪驾订单-' . $orderInfo['menu_name'],
                    'keyword3' => $orderInfo['username'],
                    'keyword4' => substr_replace($orderInfo['mobile'], '****', 3, 4) . ' (如有任何疑问，请联系客服：15000385599)',
                ];
                foreach ($openIdArr as $openid) {
                    $weiXinOfficialService->sendTemplateMsg(
                        $openid,
                        WeiXinOfficialService::NEW_ORDER,
                        $domain . '/partner/#/pages/tabbar/orderTaking',
                        '',
                        $data
                    );
                }
            }
            // 验车订单
            if ($orderInfo['order_type'] == 2) {
                $openIdArr = UserPartnerModel::whereIn('user_type', [1, 2])
                    ->where('status', 1)
                    ->where('is_forbid', 0)
                    ->where('openid', '<>', '')
                    ->where('city', $orderInfo['city_id'])
                    ->column('openid');
                $data = [
                    'keyword1' => $orderInfo['order_sn'],
                    'keyword2' => '验车订单-' . $orderInfo['menu_name'],
                    'keyword3' => $orderInfo['username'],
                    'keyword4' => $orderInfo['mobile'] . ' (如有任何疑问，请联系客服：15000385599)',
                ];
                foreach ($openIdArr as $openid) {
                    $weiXinOfficialService->sendTemplateMsg(
                        $openid,
                        WeiXinOfficialService::NEW_ORDER,
                        $domain . '/partner/#/pages/tabbar/orderTaking',
                        '',
                        $data
                    );
                }
            }
        }
        // 用户取消订单
        if ($msgType == 'cancel_order') {
            $orderInfo = EscortMenuReserveOrderModel::with('menuOrder')->find($id);
            if ($orderInfo['coach_user_id']) {
                $openid = UserPartnerModel::where('id', $orderInfo['coach_user_id'])->value('openid');
                $weekdays = ['日', '一', '二', '三', '四', '五', '六'];
                $date = date('Y年m月d日', $orderInfo['reserve_time']);
                $weekday = $weekdays[date('w', $orderInfo['reserve_time'])];
                $time = date('H:i', $orderInfo['reserve_time']);
                $data = [
                    'keyword1' => $orderInfo['username'],
                    'keyword2' => $date . '-' . $weekday . '(' . $time . ')',
                    'keyword3' => $orderInfo['order_type'] == 1 ? '陪驾订单' : '验车订单' . '-' . $orderInfo['menu_name'],
                ];
                $weiXinOfficialService->sendTemplateMsg(
                    $openid,
                    WeiXinOfficialService::CANCEL_ORDER,
                    $domain . '/partner/#/pages/tabbar/orderTaking',
                    '',
                    $data
                );
            }
        }
        // 提现申请
        if ($msgType == 'apply_withdraw') {
            // 陪驾验车教练提现
            if ($data['type'] == 0) {
                $orderInfo = PartnerWithdrawRecordModel::find($id);
                $title = $orderInfo['type'] == 1 ? '支付宝余额' : '微信余额';
                $money = UserPartnerModel::where('id', $orderInfo['user_id'])->value('money');
                $openid = UserPartnerModel::where('id', $orderInfo['user_id'])->value('openid');
                $url = $domain . '/partner/#/pages/my/purse';
            } else {
                $orderInfo = CoachWithdrawRecordModel::find($id);
                $title = '微信余额';
                $money = UserCoachModel::where('id', $orderInfo['user_id'])->value('money');
                $openid = UserCoachModel::where('id', $orderInfo['user_id'])->value('openid');
                $url = $domain . '/coach/#/pages/my/mypurse';
            }
            $data = [
                'keyword1' => $orderInfo['money'],
                'keyword2' => date('Y年m月d日 H:i', $orderInfo['create_time']),
                'keyword3' => $money,
                'keyword4' => $title,
            ];
            $weiXinOfficialService->sendTemplateMsg(
                $openid,
                WeiXinOfficialService::WITHDRAW_APPLY,
                $url,
                '',
                $data
            );
        }
        // 提现成功
        if ($msgType == 'success_withdraw') {
            // 陪驾验车教练提现
            if ($data['type'] == 0) {
                $orderInfo = PartnerWithdrawRecordModel::find($id);
                $openid = UserPartnerModel::where('id', $orderInfo['user_id'])->value('openid');
                $url = $domain . '/partner/#/pages/my/purse';
            } else {
                $orderInfo = CoachWithdrawRecordModel::find($id);
                $openid = UserCoachModel::where('id', $orderInfo['user_id'])->value('openid');
                $url = $domain . '/coach/#/pages/my/mypurse';
            }
            $data = [
                'keyword1' => $orderInfo['money'],
                'keyword2' => '提现成功',
                'keyword3' => date('Y年m月d日 H:i', time()),
            ];
            $weiXinOfficialService->sendTemplateMsg(
                $openid,
                WeiXinOfficialService::WITHDRAW_SUCCESS,
                $url,
                '',
                $data
            );
        }
        return true;
    }

}